import 'package:fish_redux/fish_redux.dart';
import 'action.dart';
import 'state.dart';
import 'model/main_view_model.dart';
import '../../app_files.dart';

Effect<MainViewState> buildEffect() {
  return combineEffects(<Object, Effect<MainViewState>>{
    MainViewAction.onTapSort: _onTapSort,
    MainViewAction.onLoad: _onLoad,
    MainViewAction.onRefresh: _onRefresh,
    MainViewAction.onCallPhone: _onCallPhone,
    MainViewAction.onGetAllOrder: _onGetAllOrder,
    MainViewAction.onNewInstall: _onNewInstall,
    Lifecycle.initState: _initState,
    MainViewAction.onTap: _onTap,
    MainViewAction.onSwitchCheckLeaderType: _onSwitchCheckLeaderType,
  });
}

void _onNewInstall(Action action, Context<MainViewState> ctx) {
  CommonUtils.presentRoute(ctx.context, RoutePath.installView);
}

void _onSwitchCheckLeaderType(Action action, Context<MainViewState> ctx) {
  ctx.state.model = null;
  ctx.dispatch(MainViewActionCreator.onAction());
  ctx.state.checkLeaderType = ctx.state.checkLeaderType == 1 ? 2 : 1;
  _sendRequest(action, ctx);
}

void _onCallPhone(Action action, Context<MainViewState> ctx) {
  String call = action.payload;
  CommonUtils.callPhone(call, ctx.context);
}

void _initState(Action action, Context<MainViewState> ctx) async {
  _sendRequest(action, ctx);
  bus.on('refreshMain', (arg) {
    ctx.state.isGsUser = false;
    ctx.dispatch(MainViewActionCreator.onAction());
    ctx.state.sortIndex = 0;
    ctx.state.multipleSelect = false;

    _sendRequest(action, ctx);
  });

  bus.on('logout', (arg) {
    ctx.state.multipleSelect = false;
    ctx.state.model = null;
    ctx.dispatch(MainViewActionCreator.onSetItems(null, 1));
  });

  bus.on('refreshList', (arg) {
    ctx.dispatch(MainViewActionCreator.onSetItems(null, 1));
    _sendRequest(action, ctx);
  });

  bus.on('setGasUser', (arg) {
    ctx.state.isGsUser = true;
    ctx.dispatch(MainViewActionCreator.onAction());
  });
}

_sendRequest(Action action, Context<MainViewState> ctx) async {
  if (ctx.state.userInfo.userid.length == 0) return;
  if (ctx.state.userInfo.isCountLeader) {
    MainViewModel safeModel;
    MainViewModel patrolModel;
    FixCountModel fixModel;
    ResultData res = await CommonNetWork.safeCountInfo();
    if (res.success) {
      safeModel = MainViewModel.fromSafeCount(res.data['data']);
    } else {
      CommonUtils.showErrorInfo(ctx.context, res.desc);
      ctx.state.refreshController.finishRefresh();
      return;
    }
    ResultData fixRes = await CommonNetWork.fixCountInfo();
    if (fixRes.success) {
      fixModel = FixCountModel.fromJson(fixRes.data['data']);
    } else {
      CommonUtils.showErrorInfo(ctx.context, fixRes.desc);
      ctx.state.refreshController.finishRefresh();
      return;
    }

    ResultData patrolRes = await CommonNetWork.patrolCountInfo();
    if (patrolRes.success) {
      patrolModel = MainViewModel.fromPatrolLeader(patrolRes.data['data']);
    } else {
      CommonUtils.showErrorInfo(ctx.context, patrolRes.desc);
      ctx.state.refreshController.finishRefresh();
      return;
    }

    ResultData totalRes = await CommonNetWork.countTotalInfo();
    if (totalRes.success) {
      CountLeaderModel model;
      model = CountLeaderModel.fromFugouSafeCount(
          totalRes.data, safeModel, fixModel, patrolModel);
      ctx.dispatch(MainViewActionCreator.onGetData(model));
      return;
    } else {
      CommonUtils.showErrorInfo(ctx.context, fixRes.desc);
      ctx.state.refreshController.finishRefresh();
      return;
    }
  }
  if (ctx.state.userInfo.isInstallWorker) {
    ResultData res = await CommonNetWork.getInstallMainInfo();
    if (res.success) {
      InstallModel installModel = InstallModel.fromJson(res.data);
      ctx.dispatch(MainViewActionCreator.onGetData(installModel));
      _loadInfo(ctx, 1);
    } else {}
    return;
  }

  if (ctx.state.userInfo.isCheckLeader) {
    ResultData res;
    if (ctx.state.checkLeaderType == 1)
      res = await CommonNetWork.safeCountInfo();
    else
      res = await CommonNetWork.patrolCountInfo();
    if (res.success) {
      MainViewModel model;
      if (ctx.state.checkLeaderType == 1)
        model = MainViewModel.fromSafeCount(res.data['data']);
      else
        model = MainViewModel.fromPatrolLeader(res.data['data']);
      ctx.dispatch(MainViewActionCreator.onGetData(model));
      _loadInfo(ctx, 1);
    } else {
      CommonUtils.showErrorInfo(ctx.context, res.desc);
    }
    return;
  }
  if (ctx.state.userInfo.isFixWorker) {
    ResultData res = await CommonNetWork.fixMainInfo(ctx.state.userInfo.userid);
    if (res.success) {
      MainViewModel model = MainViewModel.fromFixUser(res.data['data']);
      ctx.dispatch(MainViewActionCreator.onGetData(model));
      _loadInfo(ctx, 1);
    } else {
      CommonUtils.showErrorInfo(ctx.context, res.desc);
    }
    return;
  }
  if (ctx.state.userInfo.isEngineer) {
    ctx.state.type = 5;
    ResultData res = await CommonNetWork.engineerMainInfo(
        ctx.state.userInfo.userid,
        type: ctx.state.userInfo.isCustomer ? '6' : '1,7,9');
    if (res.success) {
      MainViewModel model = MainViewModel.fromFixUser(res.data['data']);
      ctx.dispatch(MainViewActionCreator.onGetData(model));
      _loadInfo(ctx, 1);
    } else {
      CommonUtils.showErrorInfo(ctx.context, res.desc);
    }
    return;
  }
  if (ctx.state.userInfo.isPatrolWorker &&
      GlobalStore.store.getState().userInfo.patrolPlantID != null) {
    ResultData res = await CommonNetWork.mainPatrolInfo();
    if (res.success) {
      MainViewModel model = MainViewModel.fromPatrolUser(res.data['data']);
      ctx.dispatch(MainViewActionCreator.onGetData(model));
      _loadInfo(ctx, 1);
      return;
    }
  }
  if (GlobalStore.store.getState().userInfo.plantID != null) {
    ResultData res = await CommonNetWork.mainInfo();
    if (res.success) {
      MainViewModel model = MainViewModel.fromSafeUser(res.data['data']);
      ctx.dispatch(MainViewActionCreator.onGetData(model));
      _loadInfo(ctx, 1);
      return;
    }
  }
  _loadInfo(ctx, 1);
  MainViewModel model = MainViewModel();
  ctx.dispatch(MainViewActionCreator.onGetData(model));
  ctx.dispatch(MainViewActionCreator.onSetItems([], 1));
}

_loadInfo(Context<MainViewState> ctx, int page) async {
  if (ctx.state.userInfo.isInstallWorker) {
    ResultData res = await CommonNetWork.getInstallList(page);
    if (res.success) {
      List data = res.data;
      List items = data.map((e) => InstallItemModel.fromJson(e)).toList();
      ctx.dispatch(MainViewActionCreator.onSetItems(items, page));
    } else {
      CommonUtils.showErrorInfo(ctx.context, res.desc);
      ctx.dispatch(MainViewActionCreator.onSetItems([], page));
    }
  } else if (ctx.state.userInfo.isCheckLeader) {
    if (ctx.state.checkLeaderType == 1) {
      ResultData res = await CommonNetWork.workerList(
        page: page,
        orderBy: ctx.state.sortIndex,
        pageSize: 99999,
      );
      ctx.state.type = 0;
      if (res.success) {
        List list = res.data['data'];
        List items = list.map((e) => LeaderItemModel.fromJson(e)).toList();
        ctx.dispatch(MainViewActionCreator.onSetItems(items, page));
      } else {
        CommonUtils.showErrorInfo(ctx.context, res.desc);
        ctx.dispatch(MainViewActionCreator.onSetItems([], page));
      }
    } else {
      ResultData res = await CommonNetWork.patrolWorkerList(
        page: page,
        orderBy: ctx.state.sortIndex,
        pageSize: 99999,
      );
      ctx.state.type = 0;
      if (res.success) {
        List list = res.data['data'];
        List items =
            list.map((e) => LeaderItemModel.fromJson(e, type: 1)).toList();
        ctx.dispatch(MainViewActionCreator.onSetItems(items, page));
      } else {
        CommonUtils.showErrorInfo(ctx.context, res.desc);
        ctx.dispatch(MainViewActionCreator.onSetItems([], page));
      }
    }
  } else {
    if (ctx.state.userInfo.isCheckWorker) {
      ResultData res =
          await CommonNetWork.communityList(status: ctx.state.sortIndex);
      ctx.state.type = 1;
      if (res.success) {
        List list = res.data['data'];
        List items = list.map((e) => CommunityItemModel.fromJson(e)).toList();
        ctx.dispatch(MainViewActionCreator.onSetItems(items, page));
      } else {
        CommonUtils.showErrorInfo(ctx.context, res.desc);
        ctx.dispatch(MainViewActionCreator.onSetItems([], page));
      }
    } else if (ctx.state.userInfo.isPatrolWorker) {
      ResultData res =
          await CommonNetWork.patrolAreaList(status: ctx.state.sortIndex);
      ctx.state.type = 3;
      if (res.success) {
        List list = res.data['data'];
        List items = list.map((e) => PatrolAreaModel.fromJson(e)).toList();
        ctx.dispatch(MainViewActionCreator.onSetItems(items, page));
      } else {
        CommonUtils.showErrorInfo(ctx.context, res.desc);
        ctx.dispatch(MainViewActionCreator.onSetItems([], page));
      }
    }else if (ctx.state.userInfo.isEngineer) {
      int orderState = ctx.state.sortIndex + 1;
      if (ctx.state.sortIndex == 2)  orderState = ctx.state.userInfo.isCustomer ? 9 : 4;
      if (ctx.state.sortIndex == 3) orderState = ctx.state.userInfo.isCustomer ? 4 : 5;

      ResultData res = await CommonNetWork.engineerOrderList(
        workId: ctx.state.userInfo.userid,
        status: orderState,
        page: page,
        pageSize: 10,
        type: ctx.state.userInfo.isCustomer ? '6' : '1,7,9',
      );
      ctx.state.type = 5;
      if (res.success) {
        List list = res.data['data'];
        print(list.length);
        List items = list.map((e) => FixListItemModel.fromJson(e)).toList();
        ctx.dispatch(MainViewActionCreator.onSetItems(items, page));
      } else {
        CommonUtils.showErrorInfo(ctx.context, res.desc);
        ctx.dispatch(MainViewActionCreator.onSetItems([], page));
      }
    } else {
      int orderState = ctx.state.sortIndex + 1;
      if (ctx.state.sortIndex == 2) orderState = 4;
      if (ctx.state.sortIndex == 3) orderState = 5;
      ResultData res = await CommonNetWork.fixOrderList(
        workId: ctx.state.userInfo.userid,
        status: orderState,
        page: page,
        pageSize: 10,
      );
      ctx.state.type = 2;
      if (res.success) {
        List list = res.data['data'];
        List items = list.map((e) => FixListItemModel.fromJson(e)).toList();
        ctx.dispatch(MainViewActionCreator.onSetItems(items, page));
      } else {
        CommonUtils.showErrorInfo(ctx.context, res.desc);
        ctx.dispatch(MainViewActionCreator.onSetItems([], page));
      }
    }
  }
}

void _onTapSort(Action action, Context<MainViewState> ctx) async {
  if (ctx.state.sortIndex == action.payload) return;
  ctx.state.sortIndex = action.payload;
  ctx.dispatch(MainViewActionCreator.setSort(action.payload));
  if (ctx.state.userInfo.isCheckLeader) {
  } else {
    _loadInfo(ctx, 1);
  }
}

void _onLoad(Action action, Context<MainViewState> ctx) async {
  await _loadInfo(ctx, action.payload);
}

void _onRefresh(Action action, Context<MainViewState> ctx) async {
  _sendRequest(action, ctx);
}

void _onGetAllOrder(Action action, Context<MainViewState> ctx) async {
  List<String> orders =
      ctx.state.selectItems.map<String>((e) => e.itemID).toList();
  CommonUtils.showWaitLoading(ctx.context);
  ResultData res = await CommonNetWork.fixGetOrder(orders.join(','));
  Navigator.pop(ctx.context);
  if (res.success) {
    await CommonUtils.showAlertView(ctx.context, '批量接单成功');
    ctx.state.multipleSelect = false;
    ctx.state.selectItems.clear();
    bus.emit('refreshList');
  }
}

void _onTap(Action action, Context<MainViewState> ctx) {
  print(action.payload);
  switch (action.payload) {
    case '户号管理':
      CommonUtils.checkUserLogin(ctx.context, () {
        CommonUtils.pushRoute(ctx.context, RoutePath.gasUserAccountView);
      });

      break;
    case '账单记录':
      CommonUtils.checkUserLogin(ctx.context, () {
        CommonUtils.pushRoute(ctx.context, RoutePath.orderListView);
      });

      break;
    case '故障报修':
      CommonUtils.pushRoute(ctx.context, RoutePath.reportProblemView);
      break;
    case '户号查询':
      CommonUtils.checkUserLogin(ctx.context, () {
        CommonUtils.pushRoute(ctx.context, RoutePath.searchAccountView);
      });

      break;
    case '燃气保险':
      CommonUtils.pushRoute(ctx.context, RoutePath.gasInsuranceView);
      break;
    case '安检记录':
      CommonUtils.checkUserLogin(ctx.context, () {
        CommonUtils.pushRoute(ctx.context, RoutePath.gasUserAccountView,
            arguments: {'type': 2});
      });
      break;
    case '服务网点':
      CommonUtils.pushRoute(ctx.context, RoutePath.storeDetailView);
      break;
    case '购气充值':
      CommonUtils.checkUserLogin(ctx.context, () {
        CommonUtils.pushRoute(ctx.context, RoutePath.gasUserAccountView,
            arguments: {'type': 3});
      });
      break;
  }
}
